package com.klm.config.interceptor;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.klm.annotation.Translate;
import com.klm.annotation.TranslateFromField;
import com.klm.client.TranslateClient;
import com.klm.request.UpdateBizIdRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.*;

@Slf4j
@Intercepts({
        @Signature(
                type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class, Integer.class}
        )
})
@Component
public class TranslateInsertInterceptor implements InnerInterceptor {

    @Autowired
    private TranslateClient translateClient;

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer i) {
        // 检查是否是insert语句
        String sql = sh.getBoundSql().getSql();
        if (sql.toLowerCase().startsWith("insert") || sql.toLowerCase().startsWith("update")) {
            // 获取参数对象
            Object parameterObj = sh.getParameterHandler().getParameterObject();
            if (sql.toLowerCase().startsWith("update")) {
                if (sh.getParameterHandler().getParameterObject() instanceof Map) {
                    HashMap<String, Object> map = (HashMap<String, Object>) parameterObj;
                    parameterObj = map.get("param1");
                } else {
                    log.warn("[Trans. plugin] ATP-TranslateInsertInterceptor-Intercept update operation, unsupported parameter types, Automatic update of business ID failed");
                }
            }
            boolean translate = false;
            if (parameterObj != null) {
                // 获取对象的类
                Class<?> clazz = parameterObj.getClass();
                // 获取类上面的注解
                Annotation[] annotations = clazz.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof Translate) {
                        translate = true;
                        break;
                    }
                }
                // 如果没有注解，则不翻译
                if (!translate) {
                    return;
                }
                String tableId = null;
                Set<String> itemKeys = new HashSet<>();
                Class<?> currentClass = parameterObj.getClass();
                Field[] fields = currentClass.getDeclaredFields();
                // 遍历对象的所有字段
                for (Field field : fields) {
                    if (field.isAnnotationPresent(TableId.class)) {
                        // 反射设置字段值为 null 或者其他默认值
                        field.setAccessible(true);
                        // 找到需要翻译的字段
                        try {
                            tableId = field.get(parameterObj).toString();
                        } catch (IllegalAccessException e) {
                            log.error("[Trans. plugin] ATP-TranslateInsertInterceptor-TableId IllegalAccessException", e);
                        }
                    } else if (field.isAnnotationPresent(TranslateFromField.class)) {
                        // 反射设置字段值为 null 或者其他默认值
                        field.setAccessible(true);
                        // 找到所有的 itemkey的值
                        try {
                            if (field.get(parameterObj) != null) {
                                itemKeys.add(field.get(parameterObj).toString());
                            }
                        } catch (IllegalAccessException e) {
                            log.error("[Trans. plugin] ATP-TranslateInsertInterceptor-TranslateFromField IllegalAccessException", e);
                        }
                    }
                }
                if (!itemKeys.isEmpty() && tableId != null) {
                    try {
                        // 为每个itemKey调用接口更新fromDataId
                        for (String itemKey : itemKeys) {
                            UpdateBizIdRequest request = new UpdateBizIdRequest();
                            request.setItemKey(itemKey);
                            request.setBizId(tableId);
                            request.setOperator("Interceptor");
                            
                            // 调用translate-server的接口更新数据
                            translateClient.executeRequest(request, HttpMethod.DELETE, Boolean.class);
                            log.debug("[Trans. plugin] Updated fromDataId for itemKey: {}, tableId: {}", itemKey, tableId);
                        }
                    } catch (Exception e) {
                        log.error("[Trans. plugin] Failed to update fromDataId for itemKeys: {}", itemKeys, e);
                    }
                }
            }
        }
    }

    @Override
    public void setProperties(Properties properties) {
        // 设置属性
    }
}
